// 前序遍历：根-左-右

function preorderTraversal(root) {
    if (!root) return [];

    let res = [], stack = [root];

    while (stack.length) {
        let node = stack.pop();
        if (node.right) stack.push(node.right);
        if (node.left) stack.push(node.left);
        res.push(node.val);
    };
    return res;
};


// test
const root = {
    val: 1,
    right: {
        val: 2,
        left: {
            val: 3,
        },
    },
};

const res = preorderTraversal(root);

console.log(res);   // [ 1, 2, 3 ]